package com.open.pdf.openpdf;

import com.lowagie.text.Document;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfPageEventHelper;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;

public class PageXofY extends PdfPageEventHelper {

    /**
     * The PdfTemplate that contains the total number of pages.
     */
    protected PdfTemplate total;

    /**
     * The font that will be used.
     */
    protected BaseFont helv;

    /**
     * 字体大小
     */
    protected int fontSize = 10;

    public PageXofY(BaseFont helv) {
        this.helv = helv;
    }

    @Override
    public void onOpenDocument(PdfWriter writer, Document document) {
        total = writer.getDirectContent().createTemplate(100, 100);
    }

    /**
     * @see com.lowagie.text.pdf.PdfPageEvent#onEndPage(com.lowagie.text.pdf.PdfWriter,
     * com.lowagie.text.Document)
     */
    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        PdfContentByte cb = writer.getDirectContent();
        cb.saveState();
        int pageNumber = writer.getPageNumber();
        String text = "" + pageNumber + " /";

        float textX = document.right() - 58;
        float textY = document.bottom() - 20;
        cb.beginText();
        cb.setFontAndSize(helv, fontSize);

        //第几页  位置
        cb.setTextMatrix(textX, textY);
        cb.showText(text);
        cb.endText();
        //计算总页数的偏量
        int offSet;
        int offSetMax5 = 100000;
        int offSetMax4 = 10000;
        int offSetMax3 = 1000;
        int offSetMax2 = 100;
        int offSetMax1 = 10;
        if (pageNumber < offSetMax1) {
            offSet = 0;
        } else if (pageNumber < offSetMax2) {
            offSet = 5;
        } else if (pageNumber < offSetMax3) {
            offSet = 12;
        } else if (pageNumber < offSetMax4) {
            offSet = 18;
        } else if (pageNumber < offSetMax5) {
            offSet = 23;
        }else{
            offSet = 28;
        }
        // 总页数 位置
        cb.addTemplate(total, textX + offSet, textY);
        cb.restoreState();


    }

    @Override
    public void onCloseDocument(PdfWriter writer, Document document) {
        total.beginText();
        total.setFontAndSize(helv, fontSize);
        total.setTextMatrix(13, 0);
        total.showText(String.valueOf(writer.getPageNumber() - 1));
        total.endText();
    }

}
